<template>
    <div>
        <van-nav-bar title="注册" />

        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="zdy.username" name="手机号" label="手机号" placeholder="手机号"
                    :rules="[{ pattern, message: '手机号长度为11' }]" />
                <van-field v-model="zdy.password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ pattern, message: '密码不少于8位' }]" />
                <van-field v-model="zdy.passwordok" type="password" name="密码" label="确认密码" placeholder="确认密码"
                    :rules="[{ validator, message: '两次密码不一致' }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    注册
                </van-button>
            </div>
            <div style="margin: 16px;">
                <van-button round block type="primary" @click="qdl">
                    已有账号,去登录
                </van-button>
            </div>
        </van-form>

    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import { registerApi } from '../request/api'
import { showToast } from 'vant'
const zdy = reactive({
    username: '',
    password: '',
    passwordok: ''
})
const pattern = /^[0-9a-zA-Z]{11}$/
const validator = (jy) => {
    if (jy != zdy.password) {
        return false
    }
    return true
}
const router = useRouter()
const onSubmit = () => {
    registerApi(zdy.username, zdy.password).then(res => {
        if (res.data.code == 0) {
            showToast({
                type: 'success',
                message: '注册成功',
                onClose() {
                    router.push('/login')
                }
            })
        } else {
            showToast({
                type: 'fail',
                message: '用户名已存在',
                onClose() {
                    zdy.username = '';
                    zdy.password = '';
                    zdy.passwordok = '';
                }
            })
        }
    })
};
const qdl = () => {
    router.push('/login')
}
</script>

<style lang="scss" scoped></style>